package sdju;

import org.apache.poi.hssf.record.cf.FontFormatting;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.autoconfigure.SpringBootApplication;


import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fantuancyh
 * @data 2020/10/20
 */
@SpringBootApplication
@EnableRabbit
public class Application {
    public static void main(String[] args) throws IOException {
        Map<String, List<Map>> stringListMap = makeData();
        //单价
        double price = 28.0;
        String filePath = "C:\\Users\\admin\\Desktop\\data2.xlsx";//文件路径
        XSSFWorkbook workbook = new XSSFWorkbook();//创建Excel文件(Workbook)

        XSSFSheet sheet = workbook.createSheet();//创建工作表(Sheet)
        List<Integer> numStep = new ArrayList<Integer>();
        XSSFRow row = sheet.createRow(0);// 创建行,从0开始
        XSSFCell cell = row.createCell(0);// 创建行的单元格,也是从0开始

        row.createCell(0).setCellValue("楼号");// 设置单元格内容
        row.createCell(1).setCellValue("房号");// 设置单元格内容,重载
        row.createCell(2).setCellValue("份数");// 设置单元格内容,重载
        row.createCell(3).setCellValue("金额");// 设置单元格内容,重载
        row.createCell(4).setCellValue("是否付款");// 设置单元格内容,重载
        int i = 0;
        double totalPrice = 0;
        int totalNumber = 0;
        for (Map.Entry<String, List<Map>> entry : stringListMap.entrySet()) {
            String key = entry.getKey();
            List<Map> lists = entry.getValue();
            XSSFRow row1 = null;
            numStep.add(lists.size());
            int num = 0;
            for (Map m : lists) {
                row1 = sheet.createRow(++i);
                String room = (String) m.get("room");
                Integer number = ((Integer) m.get("number"));
                totalNumber = totalNumber + number;
                num = num + number;
                row1.createCell(0).setCellValue(key+"号楼");
                row1.createCell(1).setCellValue(Integer.parseInt(room));
                row1.createCell(2).setCellValue((number));
                row1.createCell(3).setCellValue(number * price);
            }
        }

        System.out.println(totalNumber);
        merge(sheet, numStep,stringListMap);
        FileOutputStream out = new FileOutputStream(filePath);
        workbook.write(out);//保存Excel文件
        out.close();//关闭文件流
        System.out.println("OK!");

    }

    public static void merge(XSSFSheet sheet, List<Integer> lists, Map<String, List<Map>> stringListMap){
        // 合并单元格
        int sum = 1;
        int lineSum=1;
        for (int i :lists) {
                if(i>1){
                    CellRangeAddress region = new CellRangeAddress(sum, (sum +i-1), 0, 0);
                    sheet.addMergedRegion(region);
                }
            sum= (sum+ i);
      }
       
        //楼栋数量总计
        for (Map.Entry<String, List<Map>> entry : stringListMap.entrySet()) {
            //单个楼栋订购总数
            BigDecimal number = entry.getValue().stream().map(e -> {
                return new BigDecimal((Integer) e.get("number"));
            }).reduce(BigDecimal.ZERO, BigDecimal::add);
            String key = entry.getKey();
            int size = entry.getValue().size();
            //合并的单元格设置内容
            sheet.getRow(lineSum).getCell(0).setCellValue(key+"号楼" + "("+number+"份)");
            lineSum= lineSum+size;
        }

    }

    public static Map<String, List<Map>> makeData() {
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        Map<String, List<Map>> units = new HashMap<>();
        try {
            File myFile = new File("C:\\Users\\admin\\Desktop\\rabbitmq\\data.txt");//通过字符串创建File类型对象，指向该字符串路径下的文件
            if (myFile.isFile() && myFile.exists()) { //判断文件是否存在
                InputStreamReader Reader = new InputStreamReader(new FileInputStream(myFile), "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(Reader);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    String str = lineTxt.toString();
                    int i = str.split(" ")[0].indexOf("、");
                    Integer id = Integer.parseInt(str.substring(0, i));
                    //unit-room
                    String um = str.split(" ")[1];
                    String[] split = new String[2];
                    if (um.contains("-")) {
                        split = um.split("-");
                    } else if (um.contains("#")) {
                        split = um.split("#");
                    }else if(um.contains("＃")){
                        split = um.split("＃");
                    }else if(um.contains("－")){
                        split = um.split("－");
                    }else if(um.contains("一")){
                        split = um.split("一");
                    }else if(um.contains("—")){
                        split = um.split("—");
                    }else if(um.contains("号")){
                        split = um.split("号");
                    }else if(um.contains("_")){
                        split = um.split("_");
                    }
                    String unit = split[0];
                    String room = split[1];

                    //数量
                    String regEx = "[^0-9]+";
                    Integer number = Integer.parseInt(str.split(" ")[2].replaceAll(regEx, ""));
                    System.out.println("id:" + id + ",单元:" + unit + ",房间:" + room + ",数量:" + number+";");
                    Map map = new HashMap();
                    map.put("id", id);
                    map.put("unit", unit);
                    map.put("room", room);
                    map.put("number", number);
                    list.add(map);
                }
                //根据房间号排序
                Collections.sort(list, new Comparator<Map<String, String>>(){
                    public int compare(Map<String, String> o1, Map<String, String> o2) {
                        String name1 = o1.get("room");
                        String name2= o2.get("room");
                        return Integer.parseInt(name1)- Integer.parseInt(name2);
                    }

                });
                //按照楼栋聚合
                units = list.stream().collect(Collectors.groupingBy(
                        (Map m) -> (String) m.get("unit")));
                Reader.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return units;
    }
}
